package com.rds.benchmark.operator;

import com.rds.benchmark.util.MakeValue;
import redis.clients.jedis.commands.JedisCommands;

import java.io.IOException;
import java.util.Date;

public class StableStringOperator extends TypeOperatorBase {

    private Object conn;

    private String key;

    private static long ErrorTimestamp = 0;

    private final String value = MakeValue.value;

    private synchronized boolean needPrint() {
        long timestamp = System.currentTimeMillis() / 2000;
        if (timestamp != ErrorTimestamp) {
            ErrorTimestamp = timestamp;
            return true;
        }
        return false;
    }

    @Override
    public void init(Object conn, String key, int idx,String mode) {
        this.conn = conn;
        this.key = key;
        ((JedisCommands)conn).set(key, value);
    }

    @Override
    public Long clear() {
        return ((JedisCommands) conn).del(key);
    }

    @Override
    public void operate() throws IOException {
        try {
            ++times;
            ((JedisCommands)conn).get(key);
        } catch (Throwable t) {
            if (needPrint()) {
                System.out.println(new Date() + " ERROR: " + t.getMessage());
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
    }
}
